//
//  RanPhotoSelectionController.m
//  testAVFoundation
//
//  Created by Ran on 15/11/5.
//  Copyright (c) 2015年 gintong. All rights reserved.
//

#import "RanPhotoSelectionController.h"
#import "RanPhotoPickerViewController.h"
#import <AssetsLibrary/AssetsLibrary.h>
#import "RanPhotoSelectionModel.h"
#import "RanPhotoSelectionCell.h"

static NSString *const CELL_REUSE_ID = @"89757";

@interface RanPhotoSelectionController ()<UICollectionViewDataSource, UICollectionViewDelegate>

@property(nonatomic, strong)NSMutableArray *dataSource;
@property(nonatomic, strong)UICollectionView *collectionview;

@property(nonatomic, weak)UIButton *previewBtn;
@property(nonatomic, weak)UIButton *confirmBtn;

@end

@implementation RanPhotoSelectionController

#pragma mark - LifeCycle

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
        
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self setupUI];
    [self loadData];
}

- (void)dealloc
{
    NSLog(@"selection dealloc");
}

#pragma mark - Private

- (void)setupUI
{
    self.view.backgroundColor = [UIColor blackColor];
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    CGFloat screenWidth = [UIScreen mainScreen].bounds.size.width;
    CGFloat screentHeight = [UIScreen mainScreen].bounds.size.height;
    CGFloat startY = [UIApplication sharedApplication].statusBarFrame.size.height + self.navigationController.navigationBar.frame.size.height;
    CGFloat toolbarHeight = 44;
    CGFloat buttonWidth = 60;
    
    UIToolbar *toolbar = ({
        UIToolbar *toolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, screentHeight - toolbarHeight, screenWidth, toolbarHeight)];
        toolbar.backgroundColor = [UIColor whiteColor];
        UIBarButtonItem *previewItem = [[UIBarButtonItem alloc] initWithCustomView:({
            UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, buttonWidth, toolbarHeight)];
            self.previewBtn = btn;
            [btn setTitle:@"预览" forState:UIControlStateNormal];
            [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
            btn;
        })];
        UIBarButtonItem *spaceItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
        UIBarButtonItem *confirmItem = [[UIBarButtonItem alloc] initWithCustomView:({
            UIButton *btn = [[UIButton alloc] initWithFrame:self.previewBtn.frame];
            self.confirmBtn = btn;
            [btn setTitle:@"确定" forState:UIControlStateNormal];
            [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];

            btn;
        })];
        toolbar.items = @[previewItem, spaceItem, confirmItem];
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(toolbarClicked)];
        [toolbar addGestureRecognizer:tap];
        toolbar;
    });
    [self.view addSubview:toolbar];

    self.collectionview = ({
        CGFloat minSpacing = 3;
        NSInteger columnNum = 4;
        CGFloat itemWidth = (screenWidth - (columnNum - 1) * minSpacing) / columnNum;
        CGFloat itemHeight = itemWidth;
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        layout.itemSize = CGSizeMake(itemWidth, itemHeight);
        layout.minimumInteritemSpacing = minSpacing;
        layout.minimumLineSpacing = minSpacing;
        UICollectionView *collectionview = [[UICollectionView alloc] initWithFrame:CGRectMake(0, startY, screenWidth, screentHeight - startY - toolbarHeight) collectionViewLayout:layout];
        collectionview.dataSource = self;
        collectionview.delegate = self;
        collectionview.contentInset = UIEdgeInsetsMake(10, 0, 20, 0);
        [collectionview registerNib:[UINib nibWithNibName:@"RanPhotoSelectionCell" bundle:nil] forCellWithReuseIdentifier:CELL_REUSE_ID];
        collectionview;
    });
    [self.view addSubview:self.collectionview];
}

- (void)loadData
{
    
    __weak typeof(self) weakSelf = self;
    [[NSOperationQueue new] addOperationWithBlock:^{
        NSDate *currentDate = [NSDate date];
        [weakSelf.assetsGroup enumerateAssetsWithOptions:NSEnumerationConcurrent usingBlock:^(ALAsset *result, NSUInteger index, BOOL *stop) {
            if (!weakSelf) {
                *stop = YES;
            }

            if (result)
            {
                NSString *assetType = [result valueForProperty:ALAssetPropertyType];
                BOOL wantVideoGetPhoto = [assetType isEqualToString:ALAssetTypePhoto] && weakSelf.pickerController.sourceType == RanPhotoPickerTypeVideoOnly;
                BOOL wantPhotoGetVideo = [assetType isEqualToString:ALAssetTypeVideo] && weakSelf.pickerController.sourceType == RanPhotoPickerTypePhotoOnly;
                if (!wantPhotoGetVideo && !wantVideoGetPhoto)
                {
                    RanPhotoSelectionModel *model = [[RanPhotoSelectionModel alloc] init];
                    model.thumbImage = [UIImage imageWithCGImage:result.thumbnail];
                    model.duration = [assetType isEqualToString:ALAssetTypeVideo]? [[result valueForProperty:ALAssetPropertyDuration] floatValue]: -1;
                    model.asset = result;
//                    if (weakSelf.dataSource) {
                        [weakSelf.dataSource addObject:model];
//                    }
                }
            }else
            {
                [[NSOperationQueue mainQueue] addOperationWithBlock:^{
                    [weakSelf.collectionview reloadData];
                [weakSelf.collectionview scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:weakSelf.dataSource.count - 1 inSection:0] atScrollPosition:UICollectionViewScrollPositionBottom animated:NO];
                    NSLog(@"用时%.0f秒", [[NSDate date] timeIntervalSinceDate:currentDate]);
                }];
            }
        }];
        
    }];

}

#pragma mark - Event

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    
}

- (void)toolbarClicked
{
    if (self.dataSource.count) {
        [self.collectionview scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:self.dataSource.count - 1 inSection:0] atScrollPosition:UICollectionViewScrollPositionBottom animated:YES];
    }
}

#pragma mark - CollectionViewDataSource

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.dataSource.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    RanPhotoSelectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:CELL_REUSE_ID forIndexPath:indexPath];
    cell.model = self.dataSource[indexPath.row];
    return cell;
}

#pragma mark - Delegate

#pragma mark CollectionViewDelegate

#pragma mark - Getter

- (NSMutableArray *)dataSource
{
    if (!_dataSource) {
        self.dataSource = [NSMutableArray array];
    }
    return _dataSource;
}

@end
